# from random import randint
# import logging
#
# from django.shortcuts import render
# from django_redis import get_redis_connection
#
# # Create your views here.
# from rest_framework.response import Response
# from rest_framework.views import APIView
#
# from meiduo_mall.libs.yuntongxun.sms import CCP
# from meiduo_mall.utils.exceptions import logger
#
# from celery_tasks.sms import tasks as sms_tasks


class SMSCodeView(APIView):

    def get(self, request, mobile):

        # 创建 链接到redis的对象
        redis_conn = get_redis_connection('verify')

        send_flag = redis_conn.get('send_flag_%s'% mobile)
        if send_flag:
            return Response({'message':'发送短信过于频繁'})

        # 生成和发送短信验证码
        sms_code = '%06d'% randint(0, 999999)
        logger.debug(sms_code)

        # 发送短信验证码
        # sms_code_expires = str(constants.SMS_CODE_REDIS_EXPIRES // 60)
        sms_code_expires = str(5)
        sms_tasks.send_sms_code.delay(mobile, sms_code, sms_code_expires)

        # CCP().send_template_sms(mobile, [sms_code, '5'],1)

        # 以下代码演示redis管道pipeline的使用
        pl = redis_conn.pipeline()
        pl.setex("sms_%s" % mobile, 300, sms_code)
        pl.setex('send_flag_%s' % mobile, 60, 1)
        # 执行
        pl.execute()

        # 响应发送短信验证码结果
        return Response({'message':'OK1'})

